class TermsController < ApplicationController
  before_filter :authenticate_user!, :except => [:index, :start_with, :show]
  before_filter :check_moderators_access, :except => [:index, :start_with, :show]
  before_filter :get_term, :only => [:show, :edit, :update, :destroy]

  def index
    @chars = Term.chars
    @terms = Term.last.page(params[:page])
  end

  def start_with
    start_with = params[:char].to_s[0]
    @terms = Term.where("name LIKE ?", "#{start_with}%").sorted.page(params[:page])
  end

  def new
    @term = Term.new
  end

  def create
    @term = Term.new(params[:term])

    if @term.save
      flash[:notice] = t('success')
      redirect_to :action => :index
    else
      render :action => :new
    end
  end

  def update
    if @term.update_attributes(params[:term])
      flash[:notice] = t('success')
      redirect_to :action => :index
    else
      render :action => :edit
    end
  end

  def destroy
    @success = @term.destroy

    respond_to do |format|
      format.html { redirect_to terms_path, :alert => t('success') } # TODO success only?
      format.js
    end
  end

  protected
    def get_term
      @term = Term.find(params[:id])
    end
end
